package com.rookieCi.qrcodefile;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.rookieCi.qrcodefile.utils.LoadDialogUtils;
import com.rookieCi.qrcodefile.utils.ZipUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TextActivity extends AppCompatActivity {
    @BindView(R.id.textView)
    public TextView textView;
    @BindView(R.id.scrollView)
    public View scrollView;
    @BindView(R.id.btnCopy)
    public Button btnCopy;
    private String text;
    private int sendType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        sendType = intent.getIntExtra("sendType", 0);
        text = intent.getStringExtra("text");
        if (sendType == 1) {
            textView.setText(text);
        } else {
            textView.setText("接收完成:" + text);
            btnCopy.setText("使用其他应用打开");
            if (text.endsWith(".xcczip")) {//需要解压
                new Thread(this::unzip).start();
            }
        }

        scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                scrollView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                int height = scrollView.getHeight();
                int textH = textView.getHeight();
                if (textH < height) {
                    ViewGroup.LayoutParams layoutParams = scrollView.getLayoutParams();
                    if (layoutParams == null) return;
                    layoutParams.height = textH;
                    scrollView.setLayoutParams(layoutParams);
                }
            }
        });
    }

    @OnClick(R.id.btnCopy)
    public void onBtnCopyClick() {
        if (sendType == 1) copyText(this, text);
        else openFile(this, new File(text));
    }

    private LoadDialogUtils dialogUtils;

    private void unzip() {
        dialogUtils = new LoadDialogUtils(this);
        runOnUiThread(() -> dialogUtils.openLoadDialog("处理文件中"));

        File file = new File(text);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            int read;
            byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, read);
            }
        } catch (FileNotFoundException e) {
            if (BuildConfig.DEBUG) e.printStackTrace();
        } catch (IOException e) {
            if (BuildConfig.DEBUG) e.printStackTrace();
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int size = outputStream.size();
        if (size <= 0) {
            runOnUiThread(() -> {
                dialogUtils.dismissDialog();
                openDialog("加载失败，没救了告辞");
            });
            return;
        }
        byte[] bytes = outputStream.toByteArray();
        ByteArrayOutputStream unzip = ZipUtils.unzip(bytes);
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (unzip == null) {
            runOnUiThread(() -> dialogUtils.dismissDialog());
            return;
        }
        bytes = unzip.toByteArray();

        String absolutePath = file.getAbsolutePath();
        File unzipFile = new File(absolutePath.substring(0, absolutePath.length() - 7));
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(unzipFile);
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        runOnUiThread(() -> dialogUtils.dismissDialog());
        if (unzipFile.exists() || unzipFile.length() > 0) {
            file.delete();
            text = unzipFile.getAbsolutePath();
            runOnUiThread(() -> textView.setText("接收完成:" + text));
        }
    }

    private void openDialog(String text) {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("呵呵哒")
                .setMessage(text)
                .setPositiveButton("确定", null)
                .create();
        alertDialog.setOnDismissListener(dialog -> onBackPressed());
        alertDialog.show();
    }

    /**
     * 复制文字到剪切板
     */
    public static void copyText(Context context, String text) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (cm == null) return;
        // 将文本内容放到系统剪贴板里。
        ClipData clipData = ClipData.newPlainText("rookieCi", text);
        cm.setPrimaryClip(clipData);

        Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show();
    }

    public static void openFile(Context context, File file) {
        String fileType = getFileType(file);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //改 7.0+以上版本
            Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, fileType);
        } else {
            intent.setDataAndType(Uri.fromFile(file), fileType);
        }

        context.startActivity(intent);
    }

    private static String getFileType(File file) {
        String name = file.getName();
        if (TextUtils.isEmpty(name)) return "*/*";
        for (int i = 0; i < MIME_MapTable.length; i++) {
            String[] strings = MIME_MapTable[i];
            if (name.endsWith(strings[0])) return strings[1];
        }
        return "*/*";
    }

    private static final String[][] MIME_MapTable = {
            //{后缀名，    MIME类型}
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".doc", "application/msword"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-javascript"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".prop", "text/plain"},
            {".rar", "application/x-rar-compressed"},
            {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"},
            {".rtf", "application/rtf"},
            {".sh", "text/plain"},
            {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"},
            {".txt", "text/plain"},
            {".wav", "audio/x-wav"},
            {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"},
            {".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/zip"},
            //{"", "*/*"}
    };
}
